package com.sxran.im.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxran.im.bean.ImException;
import com.sxran.im.bean.NotificationBody;
import com.sxran.im.controller.ImController;
import com.sxran.im.dao.ImFriendInviteMapper;
import com.sxran.im.dao.ImFriendMapper;
import com.sxran.im.dao.ImUserMapper;
import com.sxran.im.info.*;
import com.sxran.im.service.FriendInviteService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AddFriendInviteCmdHandler extends AbstractCmdHandler<ImFriendInvite>{

    @Resource
    private ImFriendInviteMapper imFriendInviteMapper;
    @Resource
    private ImFriendMapper imFriendMapper;
    @Resource
    private ImUserMapper imUserMapper;
    @Resource
    private FriendInviteService friendInviteService;
    @Override
    public Object doBeanService(ImFriendInvite bean) {
        String curUserId = ImController.getCurUserId();
        String toUid = bean.getToUid();
        //
        if (StrUtil.equals(curUserId,toUid)) {
            throw new ImException("不能加自己为好友",10025);
        }
        if (imUserMapper.selectById(toUid) == null) {
            throw new ImException("对应用户不存在",10025);
        }
        //
        LambdaQueryWrapper<ImFriend> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImFriend::getFriendUid,toUid);
        queryWrapper.eq(ImFriend::getUserId,curUserId);
        if (imFriendMapper.exists(queryWrapper)) {
            throw new ImException("已经是好友",10025);
        }
        // TODO 检查是不是黑名单...

        // 不存在就添加，存在就更新
        bean.setFromUid(curUserId);
        ImFriendInvite imFriendInvite = friendInviteService.updateOrInsert(bean);
        // 通知
        NotificationBody notificationBody = new NotificationBody();
        notificationBody.setTargetList(new String[]{
                toUid
        });
        notificationBody.setContent(bean.getMessage());
        return notificationBody;
    }


}
